package com.pearl.nacos.config.demo.config;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import org.apache.commons.lang3.StringUtils;
import org.apache.shardingsphere.driver.jdbc.core.driver.ShardingSphereDriverURLProvider;

import java.nio.charset.StandardCharsets;
import java.util.Properties;

/**
 * @author TD
 * @version 1.0
 * @date 2024/4/25
 */
public class NacosDriverURLProvider implements ShardingSphereDriverURLProvider {

    private static final String NACOS_TYPE = "nacos:";

    /**
     * url 包含了 nacos: 时
     * 表示使用当前类加载配置
     */
    @Override
    public boolean accept(String url) {
        return StringUtils.isNotBlank(url) && url.contains(NACOS_TYPE);
    }

    @Override
    public byte[] getContent(String url) {
        // 参数
        String serverAddr = "localhost";
        String dataId = StringUtils.substringAfter(url, NACOS_TYPE);
        String group = "DEFAULT_GROUP";

        // 属性
        Properties properties = new Properties();
        properties.put(PropertyKeyConst.SERVER_ADDR, serverAddr);

        // 获取配置
        ConfigService configService = null;
        String content = null;
        try {
            configService = NacosFactory.createConfigService(properties);
            content = configService.getConfig(dataId, group, 5000);
        } catch (NacosException e) {
            throw new RuntimeException(e);
        }
        System.out.println(content);
        return content.getBytes(StandardCharsets.UTF_8);
    }
}
